using System;
using System.Linq;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Wolfpack.Core.Checks;
using Wolfpack.Core.Interfaces.Entities;
using Wolfpack.Core.Notification;

namespace Wolfpack.Contrib.Checks.MongoDb
{
    public class MongoLogsCheck : HealthCheckBase<MongoLogsCheckConfig>
    {
        private MongoDatabase _database;

        public MongoLogsCheck(MongoLogsCheckConfig config) : base(config)
        {
        }

        public override void Initialise()
        {
            var connectionString = string.Format("mongodb://{0}", _config.MongoLogServerName);
            var client = new MongoClient(connectionString);
            _database = client.GetServer().GetDatabase(_config.MongoLogDatabase);
        }

        public override void Execute()
        {
            var queueCount = GetExceptionCount();

            Publish(NotificationRequestBuilder.For(_config.NotificationMode, HealthCheckData.For(Identity,
                "There are {0} error messages in the {1} mongo logs", queueCount, _config.Environment)
                .ResultIs(queueCount == 0)).Build());
        }

        private int GetExceptionCount()
        {
            var previousMinutesToCheck = _config.NumberOfMinutesPreviousToCheck;

            if (_config.NumberOfMinutesPreviousToCheck > 0)
            {
                previousMinutesToCheck = 0 - _config.NumberOfMinutesPreviousToCheck;
            }

            return _database.GetCollection<Poller>("log4net").AsQueryable()
                .Where(p => p.level == "ERROR")
                .Count(x => x.timestamp >= DateTime.Now.ToUniversalTime().AddMinutes(previousMinutesToCheck));
        }

        protected override PluginDescriptor BuildIdentity()
        {
            return new PluginDescriptor
            {
                Description = "Mongo Logs HealthCheck",
                Name = _config.FriendlyId,
                TypeId = new Guid("1215E649-6B13-4479-A8A0-7DD2D4E31A46")
            };
        }
    }
}